﻿using System;
using System.Net;
using System.ServiceModel;
using System.Threading;
using System.Xml.Serialization;

namespace Galaktika.BI.Silverlight.ClientApp
{
    public static class ServiceManager
    {
        public static T CreateService<T, Base>()
            where T : ClientBase<Base>, Base, new()
            where Base : class
        {
            T client = new T();
            //InitUrl<T, Base>(client);

            return client;
        }

        [Obsolete("Не использовать!")]
        private static void InitUrl<T, Base>(T client)
            where T : ClientBase<Base>, Base, new()
            where Base : class
        {
            if (m_Settings != null && !string.IsNullOrEmpty(m_Settings.BaseUri))
            {
                try
                {
                    Uri uri = client.Endpoint.Address.Uri;
                    string srvName = uri.LocalPath.Remove(0, 1);
                    client.Endpoint.Address = new EndpointAddress(new Uri(new Uri(m_Settings.BaseUri), srvName));
                }
                catch (Exception exc)
                {
                    App.CurrentApp.LogError(exc);
                }
            }
        }


        public static void Initialize(Settings settings)
        {
            m_Settings = settings;
        }

        static Settings m_Settings;
    }

    [XmlRoot(Namespace = Common.Namespace)]
    public class Settings
    {
        public Settings()
        { 
        }

        [XmlElement]
        public string BaseUri { get; set; }
    }
}
